<?php
namespace app\Socketio\controller;

use app\BaseController;
use think\facade\View;

// todo socket.io
require_once "d:www/thinkphp6/vendor/workerman/phpsocket.io/src/autoload.php";

use Workerman\Worker;
use PHPSocketIO\SocketIO;

// 学习 socketio 通讯
class Index extends BaseController
{

    private $users;
    private $usersNum;

    // phpsocketio
    public function index(){
        $io = new SocketIO(8888);
        $io->on('connection', function ($socket) use ($io) {
            // todo 连接成功后，会静默发送connect状态
            echo "-----连接成功----->" . PHP_EOL;

            // 监听 login
            $socket->on('login', function ($msg) use ($io, $socket) {
                $username = $msg['username'];
                $group_id = $msg['group_id'];

                var_dump($group_id);

                // 加入分组
                $socket->join($group_id);
                $socket->username = $username;

                // 向某个分组的所有客户端发送事件; 聊天室通知Mike上线
                $io->to($group_id)->emit('success', json_encode($msg));
                // 向所有客户端发送事件
                // $io->emit('success', json_encode($msg));
                // 向当前客户端发送事件
                // $socket->emit('success', json_encode($msg));
            });

            // 监听 group 聊天室
            $socket->on('group', function ($msg) use ($io, $socket) {
                $group_id = $msg['group_id'];
                // 向某个分组的所有客户端发送事件
                $io->to($group_id)->emit('group message', json_encode($msg));
            });

            // 一对一私聊
            $socket->on('private chat', function ($msg) use ($io, $socket) {
                echo date('Y-m-d H:i:s') . " 收到私聊消息：" . json_encode($msg, 256) . PHP_EOL;
                echo $msg['to_id'] . PHP_EOL;
                $io->to($msg['to_id'])->emit('private chat', json_encode($msg));
            });

            // 关闭页面/离开聊天室
            $socket->on('disconnect', function () use ($socket) {
                if (!isset($this->users[$socket->username])) {
                    $this->users[$socket->username] = 0;
                }
                --$this->users[$socket->username];
                if ($this->users[$socket->username] <= 0) {
                    echo $socket->username . ' 离开了' . PHP_EOL;
                    unset($this->users[$socket->username]);
                    --$this->usersNum;
                    // 离开分组
                    $socket->leave($socket->username);
                    $res = [
                        'username'     => $socket->username,
                        'usersNum'     => $this->usersNum,
                        'currentUsers' => $this->users,
                        'type'         => 'left',
                    ];
                    $socket->broadcast->emit('sendMsg', json_encode($res, 256));
                    echo date('Y-m-d H:i:s') . " {$socket->username} leave离开了" . PHP_EOL;
                }
            });
        });
        Worker::runAll();
    }

}

